package com.zzwx.controller.context;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.cglib.beans.BeanGenerator;

@SuppressWarnings({"rawtypes","unused","unchecked"})
public class ObjectUtil {

    /**
     * 数据库字段和java字段的转换，会把数据库字段中的下划线去掉，并字母大写
     *
     * @param dbField
     * @return
     */
    public static String dbFiled2BeanField(String dbField) {
        int len = 0;
        if (dbField == null || (len = dbField.length()) == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        char[] chars = dbField.toLowerCase().toCharArray();
        boolean upcase = false;
        for (int i = 0; i < len; i++) {
            char c = chars[i];
            if (c == '_') {
                if (i != 0) {
                    upcase = true;
                }
                continue;
            }
            if (upcase) {
                if (c >= 'a' && c <= 'z') {
                    int tmp = c - 32;
                    c = (char) tmp;
                    upcase = false;
                }
            }
            sb.append((char) c);
        }
        return sb.toString();
    }

    /**
     * 将数据库查询出的字段信息转换成bean
     *
     * @param bean
     * @param map
     * @throws Exception
     */
    public static void dbFiledMap2Bean(Object bean, Map map) throws Exception {
        if (bean == null || map == null) {
            return;
        }
        Map result = new HashMap();
        
		Iterator itr = map.keySet().iterator();
        while (itr.hasNext()) {
            Object key = itr.next();
            Object value = map.get(key);
            result.put(dbFiled2BeanField(key.toString()), value);
        }
        javaFiledMap2Bean(bean, result);
    }

    /**
     * 将数据库查询出来的数据转换成bean
     *
     * @param bean
     * @param data
     * @return
     * @throws Exception
     */
    public static List dbFiledMap2Bean(Class bean, List<Map<String, Object>> data) throws Exception {
		List<Object> result = new ArrayList();
        if (bean == null || data == null) {
            return result;
        }
        Iterator<Map<String, Object>> itr = data.iterator();
        while (itr.hasNext()) {
            Map<String, Object> map = itr.next();
            Object o = bean.newInstance();
            ObjectUtil.dbFiledMap2Bean(o, map);
            result.add(o);



        }
        return result;
    }

    /**
     * 字段转换成bean 字段属�?�命名复合java规范
     *
     * @param bean
     * @param map
     * @throws Exception
     */
    public static void javaFiledMap2Bean(Object bean, Map map) throws Exception {
        if (bean == null || map == null) {
            return;
        }
        BeanUtils.populate(bean, map);
    }

    /**
     * 将bean转换为map
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public static Map bean2Map(Object bean) throws Exception {
        if (bean == null) {
            return new HashMap();
        }
        return BeanUtils.describe(bean);
    }

    public static Object generateObject(Map<String,Class> properties) {
        BeanGenerator generator = new BeanGenerator();
        Set keySet = properties.keySet();
        for (Iterator i = keySet.iterator(); i.hasNext();) {
            String key = (String) i.next();
            generator.addProperty(key, properties.get(key));
        }
        return generator.create();
    }

    /**
     * 拷贝属�??
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target);
    }

    public static void copyProperties(Object source, Object target, Class<?> editable) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, editable);
    }

    public static void copyProperties(Object source, Object target, String[] ignoreProperties) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
    }
    /**
     * json转换成对�?
     * @param JSONObject
     * @param clazz
     * @return
     * @throws Exception
     */
    public static Object jsonToObject(JSONObject jb,Class<?> clazz) throws Exception{
		Field[] fields = clazz.getDeclaredFields();
		
		Method[] ms=clazz.getMethods();
		Object object=clazz.newInstance();
		for(int j=0;j<fields.length; j++){
			Field field=fields[j];
			String fieldName=field.getName();
			Object fieldValue = jb.get(fieldName);
			if(null!=fieldValue){
				//获得设置方法
				String methodName = "set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
				Method method=clazz.getDeclaredMethod(methodName, field.getType());
				if(null!=method)
				method.invoke(object,fieldValue);
			}
		}
		return object;
    }
    /**
     * json数组转换成对象集�?
     * @param jSONArray
     * @param clazz
     * @return
     * @throws Exception
     */
    public static List jsonArrToObject(JSONArray jSONArray,Class<?> clazz) throws Exception{
    	List list=new ArrayList();
    	for(int i=0;i<jSONArray.size();i++){
    		JSONObject jb= jSONArray.getJSONObject(i);
    		Object object=clazz.newInstance();
    		/*Field[] fields = clazz.getDeclaredFields();
    		for(int j=0;j<fields.length; j++){
    			Field field=fields[j];
    			String fieldName=field.getName();
    			Object fieldValue = jb.get(fieldName);
    			if(null!=fieldValue){
    				//获得设置方法
    				String methodName = "set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
    				Method method=clazz.getDeclaredMethod(methodName, field.getType());
    				if(null!=method)
    				method.invoke(object,fieldValue);
    			}
    		}
    		*/
    		BeanUtils.populate(object, jb);
    		list.add(object);
    	}
    	return list;
    }
}
